<?php

namespace app\api\controller\v1;

use app\api\base\ApiBase;
use app\api\model\UserModel;
use think\exception\ValidateException;
use think\facade\Db;
use think\facade\Request;
use think\Request as AllRequest;
use app\api\service\serv\UserService;

class UserController extends ApiBase
{
    /***
     * @var string[]
     * @Author Vee7
     * @Date 2021/12/23
     * @Time 18:05
     * @Description 不需要登录方法,这里表示reg和login方法不进行token验证
     */
    protected $noAuth = ['reg','login'];
    /**
     * @var string[]
     * 当请求save方法时（资源路由下POST请求即为save）需要进行sign签名认证
     */
    protected $needSign = ['save'];

    /***
     * @return \think\Response
     * @Author Vee7
     * @Date 2021/12/23
     * @Time 14:07
     * @Description 查询所有数据
     */
    public function index(AllRequest $req)
    {
        $responseData = [
            '收到的数据' => $req->param('data'),
            '请求的用户' => $req->apiUserInfo
        ];
        return self::Success($responseData);
    }

    /***
     * @return \think\Response
     * @Author Vee7
     * @Date 2021/12/23
     * @Time 14:09
     * @Description 新增数据
     */
    public function create()
    {
        return self::Success('新增数据');
    }

    /***
     * @return \think\Response
     * @Author Vee7
     * @Date 2021/12/23
     * @Time 14:09
     * @Description 批量新增或更新
     */
    public function save()
    {
        return self::Success('批量新增或更新');
    }

    /***
     * @return \think\Response
     * @Author Vee7
     * @Date 2021/12/23
     * @Time 14:09
     * @Description 查询单条数据
     */
    public function read($id)
    {
        return self::Success('查询单条数据');
    }

    /***
     * @param $id
     * @return \think\Response
     * @Author Vee7
     * @Date 2021/12/23
     * @Time 14:11
     * @Description 强制修改一条数据，force()->save()
     */
    public function edit($id)
    {
        return self::Success('强制修改一条数据');
    }

    /***
     * @param $id
     * @return \think\Response
     * @Author Vee7
     * @Date 2021/12/23
     * @Time 14:12
     * @Description 更新一条数据 save()
     */
    public function update($id)
    {
        return self::Success('更新一条数据');
    }

    /***
     * @param $id
     * @return \think\Response
     * @Author Vee7
     * @Date 2021/12/23
     * @Time 14:10
     * @Description 删除单条数据
     */
    public function delete($id)
    {
        return self::Success('删除单条数据');
    }

    /***
     * @return \think\Response
     * @Author Vee7
     * @Date 2021/12/23
     * @Time 18:04
     * @Description 注册api接口用户
     * @throws \think\exception\PDOException
     */
    public function reg(){

        $request = Request::param();
        try {
            validate(\app\api\validate\User::class)
                ->scene('register')
                ->check($request);
        } catch (ValidateException $e) {
            // 验证失败 输出错误信息
            return  $this->Success(null,$e->getError(), 404);
        }

        $userData = [];
        if(!request()->has('email')){
            $userData['email'] = 'null';
        }
        if(!request()->has('mobile')){
            $userData['mobile'] = 'null';
        }
        if(!request()->has('avatar_src')){
            $userData['avatar_src'] = 'null';
        }
        $data = [
            'email' => $userData['email'],
            'mobile' => $userData['mobile'],
            'username' => $request['username'],
            'avatar_src' => $userData['avatar_src'],
            'password' => password_hash($request['password'],PASSWORD_DEFAULT),
            'create_ip' => Request::ip(),
            'status' => 1,
            'type_id' => 1,
        ];
        Db::startTrans();
        try {
            $user = new UserModel();
            $user->save($data);
            // 提交事务
            Db::commit();
            return  $this->Success(null,'注册成功！', 200);
        } catch (\Exception $e) {print_r($e);exit;
            // 回滚事务
            Db::rollback();
            return  $this->Success(null,'注册失败！', 10005);
        }
    }

    /***
     * @param UserService $user
     * @return \think\Response
     * @Author Vee7
     * @Date 2021/12/23
     * @Time 18:04
     * @Description 用户登录，登陆成功返回sign/时间戳/当前用户
     */

     //下面注释块用于生成接口文档
     //说明：
     //1.安装Apidoc 命令：npm install apidoc -g
     //2.进入项目根目录 apidoc -i 项目目录/ -o apidoc/ 例：apidoc -i app/api/controller/v1 -o public/
     //3.文档将生成在public/apidoc/index.html

    /**
     * @api {post} /login  登陆接口
     * @apiParam {String} email  邮箱（选填）.
     * @apiParam {String} password     密码（必填）.
     * @apiParam {Number} header.did     设备唯一标识（必填）.
     * @apiParam {String} header.version     系统版本号（必填）.
     */
    public function login(UserService $user)
    {
        $request = Request::param();
        try {
            validate(\app\api\validate\User::class)
                ->scene('login')
                ->check($request);
        } catch (ValidateException $e) {
            // 验证失败 输出错误信息
            return  self::Success(null,$e->getError(), 404);
        }
        $result = $user->checkLogin($request['username'],$request['password']);
        return self::Success($result['data'],$result['msg'], $result['code']);
        //登陆成功后，前端需要将获得的签名放在header中sign参数中

    }

}
